package com.cucheng.chatroom.service.impl;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cucheng.chatroom.model.po.UserInfo;
import com.cucheng.chatroom.model.vo.ResponseJson;
import com.cucheng.chatroom.service.SecurityService;
import com.cucheng.chatroom.service.UserInfoService;
import com.cucheng.chatroom.util.Constant;

@Service
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private UserInfoService userInfoService;

    private static final Logger LOGGER = LoggerFactory.getLogger (SecurityServiceImpl.class);

    /**
     *@Description: TODO(用户登录入口) 
     *@Author: wangchengjie
     *@Since: 2019年3月30日下午3:36:13
     *@param username
     *@param password
     *@param session
     *@return
     */
    @Override
    public ResponseJson login(String username,String password,HttpSession session){
        try {
            UserInfo userInfo = userInfoService.getByUsername (username);
            if (userInfo == null) { return new ResponseJson ().error ("不存在该用户名"); }
            if (!userInfo.getPassword ().equals (password)) { return new ResponseJson ().error ("密码不正确"); }
            session.setAttribute (Constant.USER_TOKEN, userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error (e.getMessage ());
        }
        return new ResponseJson ().success ();
    }

    /**
     *@Description: TODO(用户退出登录入口) 
     *@Author: wangchengjie
     *@Since: 2019年3月30日下午3:36:35
     *@param session
     *@return
     */
    @Override
    public ResponseJson logout(HttpSession session){
        try {
            Object userId = session.getAttribute (Constant.USER_TOKEN);
            if (userId == null) { return new ResponseJson ().error ("请先登录！"); }
            session.removeAttribute (Constant.USER_TOKEN);
            LOGGER.info (MessageFormat.format ("userId为 {0} 的用户已注销登录!", userId));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error (e.getMessage ());
        }
        return new ResponseJson ().success ();
    }

}
